package com.atldy.commerce.async.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.atldy.commerce.async.AsyncService;
import com.atldy.commerce.commence.goods.GoodsInfo;
import com.atldy.commerce.enums.AsyncTaskStatus;
import com.atldy.commerce.utlis.RedisUtils;
import com.atldy.commerce.vo.AsyncTaskInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Author: lidongyang
 * @CreateTime: 2021-08-19 7:31
 * @Description： 异步任务管理器
 */
@Slf4j
@Component
public class AsyncTaskManager {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private AsyncService asyncService;

    /**
     * 初始化异步信息
     */
    AsyncTaskInfo initTask() {
        AsyncTaskInfo taskInfo = new AsyncTaskInfo();
        String objectId = IdUtil.getSnowflake(1, 1).nextIdStr();
        Date date = new Date();
        taskInfo.setStatus(AsyncTaskStatus.STARTED);
        taskInfo.setTaskId(objectId);
        taskInfo.setStartTime(date);

        //初始化的异步信息存储到redis容器中
        redisUtils.set(taskInfo.getTaskId().toString(), taskInfo);
        return taskInfo;
    }

    /**
     * 执行异步任务
     */
    public AsyncTaskInfo submit(List<GoodsInfo> goodsInfos) {
        AsyncTaskInfo taskInfo = initTask();
        asyncService.asyncAddGoodsInfo(goodsInfos, taskInfo.getTaskId());
        return taskInfo;
    }

    /**
     * 提供获取异步任务信息
     */
    public AsyncTaskInfo getAsyncTaskInfo(String taskId) {
        return Convert.convert(AsyncTaskInfo.class, (redisUtils.get(taskId)));
    }

    /**
     * 提供设置异步任务信息
     */
    public void setAsyncTaskInfo(AsyncTaskInfo asyncTaskInfo) {
        redisUtils.set(asyncTaskInfo.getTaskId(), asyncTaskInfo);
    }

}